<template>
  <div class="login-container">
    <div class="login-box">

      <div class="logo">
        <span class="logo-cloud">育种材料大数据管理系统</span>
      </div>

      <div class="welcome-text">
        Breeding Material Big Data Management System
      </div>

      <el-form :model="form" class="login-form" :rules="rules" ref="loginFormRef">
        <el-form-item prop="account">
          <el-input
              v-model="form.account"
              placeholder="邮箱"
              prefix-icon="el-icon-message"
          />
        </el-form-item>

        <el-form-item prop="pass_word">
          <el-input
              v-model="form.pass_word"
              placeholder="密码"
              type="password"
              prefix-icon="el-icon-lock"
              show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer-links">
        <el-link @click="handleRegister">注册</el-link>
        <el-link @click="handleForgotPassword">忘记密码</el-link>
      </div>

      <div class="language-selector">
        <el-link>简体中文</el-link>
      </div>
    </div>

    <el-dialog
        v-model="resultDialogVisible"
        :title="resultDialogTitle"
        width="30%"
        @close="countdownTimer && clearInterval(countdownTimer)"
        center
    >
      <div style="text-align: center">
        <span style="display: block">{{ resultDialogMessage }}</span>
        <div v-if="isSuccessDialog && countdown > 0" style="margin-top: 10px;">
          将在 {{ countdown }} 秒后自动跳转...
        </div>
      </div>
      <template #footer>
        <div style="text-align: center">
          <el-button
              @click="isSuccessDialog ? navigateImmediately() : resultDialogVisible = false"
          >
            {{ isSuccessDialog ? '点击立即跳转' : 'OK' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onBeforeUnmount } from 'vue'
import { login } from '~/composables/useAuth'
import { LoginForm, UserForm } from '~/types/user'
import { loginTask } from "~/api/loginApi";
import { useRouter, useRoute } from 'vue-router'
import { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const route = useRoute()
const loginFormRef = ref<FormInstance>()

const resultDialogVisible = ref(false)
const resultDialogTitle = ref('')
const resultDialogMessage = ref('')
const loading = ref(false)
const countdown = ref(5) // 倒计时秒数
let countdownTimer: number | null = null // 倒计时定时器

const user = ref<UserForm>()

const form = reactive<LoginForm>({
  account: '',
  pass_word: ''
})

const rules = reactive<FormRules<LoginForm>>({
  account: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
  pass_word: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
})

// 获取重定向路径
const getRedirectPath = () => {
  const redirect = Array.isArray(route.query.redirect)
      ? route.query.redirect[0]
      : route.query.redirect
  return redirect || '/'
}

const handleLogin = async () => {
  try {
    await loginFormRef.value?.validate()
    loading.value = true

    const formData = new FormData()
    formData.append('account', form.account)
    formData.append('pass_word', form.pass_word)

    const response = await loginTask(formData)

    if (response.success) {
      // 登录成功处理
      login(response.data as UserForm)
      showSuccessDialog(response.msg || '登录成功')
      user.value = response.data as UserForm

      // 开始倒计时
      startCountdown()
    } else {
      showErrorDialog(response.msg || '登陆失败！用户名或密码错误')
    }
  } catch (error) {
    showErrorDialog('登录错误！')
  } finally {
    loading.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 5 // 重置倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }

  countdownTimer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(countdownTimer as number)
      navigateAfterLogin()
    }
  }, 1000)
}

// 登录后跳转逻辑
const navigateAfterLogin = () => {
  const redirectPath = getRedirectPath()
  router.push(redirectPath)
}

// 立即跳转
const navigateImmediately = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  navigateAfterLogin()
}

const isSuccessDialog = ref(false)

// 显示成功对话框（带倒计时）
const showSuccessDialog = (message: string) => {
  resultDialogTitle.value = 'Success'
  resultDialogMessage.value = message
  resultDialogVisible.value = true
  isSuccessDialog.value = true
}

// 显示错误对话框（不带倒计时）
const showErrorDialog = (message: string) => {
  resultDialogTitle.value = 'Error'
  resultDialogMessage.value = message
  resultDialogVisible.value = true
  isSuccessDialog.value = false
}

const handleRegister = () => {
  router.push('/Signup')
}

const handleForgotPassword = () => {
  router.push('/Forget')
}

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  margin: 0 200px 0px 200px;
  align-items: center;
  min-height: 100vh;
  min-widtht: 120vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 550px;
  height: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.logo {
  margin-bottom: 20px;
  font-size: 32px;
  font-weight: bold;
}

.logo-cloud {
  color: #606266;
}

.welcome-text {
  margin-bottom: 30px;
  color: #909399;
  font-size: 16px;
}

.login-form {
  margin-top: 30px;
}

.login-btn {
  width: 100%;
  margin-top: 10px;
  background-color: #1b9382;
  border: none;
}

.footer-links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.language-selector {
  margin-top: 30px;
  text-align: center;
}

.el-link {
  margin: 0 10px;
}
</style>